package com.jwiki.app.rpcui.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.springframework.util.CollectionUtils;

import com.jwiki.app.rpcui.util.handler.XmlHandler;

public abstract class XmlUtils {

    public static final String DEFAULT_ENCODING = "UTF-8";

    public static final String INDENT_STRING = "	";

    public static Document getDocument(File xml) throws DocumentException {
        return getDocument(xml, null);
    }

    public static Document getDocument(File xml, Map<String, String> namespace) throws DocumentException {
        SAXReader xmlReader = new SAXReader();
        if (!CollectionUtils.isEmpty(namespace)) {
            xmlReader.getDocumentFactory().setXPathNamespaceURIs(namespace);
        }
        return xmlReader.read(xml);
    }

    public static void saveDocument(File xml, Document xmlDoc) throws IOException {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding(DEFAULT_ENCODING);
        format.setIndent(INDENT_STRING);
        format.setNewLineAfterDeclaration(false);
        format.setPadText(false);
        XMLWriter writer = new XMLWriter(new FileOutputStream(xml), format);
        writer.write(xmlDoc);
        writer.close();
    }

    public static void readAndSave(File xml, Map<String, String> namespace, XmlHandler handler) throws Exception {
        Document xmlDoc = getDocument(xml, namespace);
        handler.handle(xmlDoc);
        saveDocument(xml, xmlDoc);
    }

    public static void readAndSave(File xml, XmlHandler handler) throws Exception {
        Document xmlDoc = getDocument(xml);
        handler.handle(xmlDoc);
        saveDocument(xml, xmlDoc);
    }

    public static void createAndSave(File xml, XmlHandler handler) throws Exception {
        Document xmlDoc = DocumentHelper.createDocument();
        handler.handle(xmlDoc);
        saveDocument(xml, xmlDoc);
    }

    public static String formatDocument(Element element) throws IOException, DocumentException {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setExpandEmptyElements(true);
        format.setNewLineAfterDeclaration(false);
        format.setPadText(false);
        format.setEncoding(DEFAULT_ENCODING);
        format.setIndent(INDENT_STRING);

        StringWriter output = new StringWriter();
        XMLWriter writer = new XMLWriter(output, format);
        writer.write(element);
        writer.close();
        String outputString = StringUtils.trim(output.toString());
        output.close();

        return outputString;
    }

}
